using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Crossborder.Extensions.Filters
{
    public class TokenFilter :  IEndpointFilter
    {
        public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)
        {
            var user = context.HttpContext.User;
            ClaimsIdentity claimsIdentity = (ClaimsIdentity)user.Identity;
            foreach (var claim in claimsIdentity.Claims)
            {
                if (claim.Type == "UserId")
                {
                    context.HttpContext.Items.Add(claim.Type, claim.Value);
                }
            }
            var result = await next(context);
            return result;
        }
    }
}